<template>
  <div class="substitute-analysis-result">
    <div class="result-header">
      <h3>替代路径分析 - {{ targetMaterial }}</h3>
      <el-button type="primary" @click="handleExport" plain>
        <el-icon><Download /></el-icon> 导出数据
      </el-button>
    </div>

    <div class="analysis-description">
      <p>本分析通过评估产品关系图中的替代路径和相似节点，识别 <strong>{{ targetMaterial }}</strong> 可能的替代方案，帮助应对材料缺失或成本上升的情况。</p>
    </div>

    <!-- 替代材料列表 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <div class="substitute-table-container">
          <h4>潜在替代材料</h4>
          <el-table
            v-if="substitutes.length > 0"
            :data="substitutes"
            border
            style="width: 100%"
            :max-height="450"
            @row-click="handleRowClick"
          >
            <el-table-column prop="potentialSubstitute" label="替代材料名称" min-width="140" sortable>
              <template #default="{ row }">
                <span class="material-name" :class="{ 'selected': row.potentialSubstitute === selectedSubstitute }">
                  {{ row.potentialSubstitute }}
                </span>
              </template>
            </el-table-column>
            
            <el-table-column prop="similarityScore" label="相似度" width="110" sortable align="center">
              <template #default="{ row }">
                <el-progress
                  :percentage="Math.round(row.similarityScore * 100)"
                  :color="getSimilarityColor(row.similarityScore)"
                  :stroke-width="15"
                />
              </template>
            </el-table-column>
            
            <el-table-column prop="commonConnections" label="共同下游" width="110" sortable align="center">
              <template #default="{ row }">
                <el-tag>{{ row.commonConnections }}</el-tag>
              </template>
            </el-table-column>
            
            <el-table-column label="供应商数" width="110" align="center">
              <template #default="{ row }">
                <el-tag :type="getSupplierCountType(row.suppliers.length)">
                  {{ row.suppliers.length }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>

          <el-empty v-else description="暂无替代材料数据" />
        </div>
      </el-col>
      
      <el-col :span="12">
        <div v-if="selectedSubstituteData" class="substitute-detail">
          <h4>{{ selectedSubstituteData.potentialSubstitute }} 详细信息</h4>
          
          <!-- 相似度卡片 -->
          <el-card class="similarity-card">
            <template #header>
              <div class="card-header">
                <span>相似度评估</span>
                <el-tag :type="getSimilarityTagType(selectedSubstituteData.similarityScore)">
                  {{ Math.round(selectedSubstituteData.similarityScore * 100) }}%
                </el-tag>
              </div>
            </template>
            <div class="similarity-metrics">
              <div class="metric">
                <div class="metric-label">共同下游产品数</div>
                <div class="metric-value">{{ selectedSubstituteData.commonConnections }}</div>
              </div>
              <div class="metric">
                <div class="metric-label">共同下游产品</div>
                <div class="metric-value common-products">
                  <el-tag
                    v-for="product in selectedSubstituteData.commonProducts"
                    :key="product"
                    size="small"
                    class="product-tag"
                  >
                    {{ product }}
                  </el-tag>
                </div>
              </div>
            </div>
          </el-card>
          
          <!-- 供应商情况 -->
          <h5>供应商情况</h5>
          <el-table
            :data="selectedSubstituteData.suppliers"
            border
            style="width: 100%"
            :max-height="200"
          >
            <el-table-column prop="name" label="企业名称" min-width="160" />
            <el-table-column prop="province" label="地区" width="80" />
            <el-table-column label="高新企业" width="80" align="center">
              <template #default="{ row }">
                <el-tag v-if="row.isHighTech" type="success">是</el-tag>
                <el-tag v-else type="info">否</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <el-empty v-else description="请选择替代材料查看详情" />
      </el-col>
    </el-row>

    <!-- 替代路径可视化 -->
    <div class="substitute-graph-container" v-if="substitutes.length > 0">
      <h4>替代路径可视化</h4>
      <div class="substitute-graph" ref="graphRef"></div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue';
import { Download } from '@element-plus/icons-vue';
import * as echarts from 'echarts';

export default {
  name: 'SubstituteAnalysisResult',
  components: {
    Download
  },
  props: {
    data: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['export'],
  setup(props, { emit }) {
    const graphRef = ref(null);
    let graphChart = null;
    
    const targetMaterial = computed(() => props.data?.targetMaterial || '');
    const substitutes = computed(() => props.data?.substitutes || []);
    const graphData = computed(() => props.data?.graphData || { nodes: [], relationships: [] });
    
    const selectedSubstitute = ref('');
    const selectedSubstituteData = computed(() => {
      return substitutes.value.find(item => item.potentialSubstitute === selectedSubstitute.value);
    });
    
    // 处理行点击
    const handleRowClick = (row) => {
      selectedSubstitute.value = row.potentialSubstitute;
      renderGraph();
    };
    
    // 获取相似度颜色
    const getSimilarityColor = (score) => {
      if (score >= 0.8) return '#67C23A'; // 绿色，高相似度
      if (score >= 0.5) return '#E6A23C'; // 黄色，中等相似度
      return '#F56C6C'; // 红色，低相似度
    };
    
    // 获取相似度标签类型
    const getSimilarityTagType = (score) => {
      if (score >= 0.8) return 'success';
      if (score >= 0.5) return 'warning';
      return 'danger';
    };
    
    // 获取供应商数量标签类型
    const getSupplierCountType = (count) => {
      if (count >= 5) return 'success';
      if (count >= 2) return 'warning';
      return 'danger';
    };
    
    // 渲染关系图
    const renderGraph = () => {
      if (!graphRef.value) return;
      
      if (graphChart) {
        graphChart.dispose();
      }
      
      graphChart = echarts.init(graphRef.value);
      
      // 准备节点数据
      const nodes = graphData.value.nodes.map(node => {
        const isTarget = node.name === targetMaterial.value;
        const isSelected = node.name === selectedSubstitute.value;
        const isCommonProduct = selectedSubstituteData.value && 
                               selectedSubstituteData.value.commonProducts.includes(node.name);
        
        return {
          id: node.id,
          name: node.name,
          symbolSize: isTarget || isSelected ? 35 : (isCommonProduct ? 20 : 15),
          value: node.name,
          category: isTarget ? 0 : (isSelected ? 1 : (isCommonProduct ? 2 : 3)),
          itemStyle: {
            color: isTarget ? '#409EFF' : 
                  (isSelected ? '#67C23A' : 
                  (isCommonProduct ? '#E6A23C' : '#909399'))
          }
        };
      });
      
      // 准备边数据
      const links = graphData.value.relationships.map(rel => {
        return {
          source: rel.source.toString(),
          target: rel.target.toString(),
          value: rel.type
        };
      });
      
      // 配置选项
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: function(params) {
            if (params.dataType === 'node') {
              const node = params.data;
              return `<div style="font-weight:bold;">${node.name}</div>`;
            } else if (params.dataType === 'edge') {
              return `${params.data.source} → ${params.data.target}`;
            }
            return '';
          }
        },
        legend: {
          data: ['目标材料', '选中替代材料', '共同下游产品', '其他节点'],
          bottom: 5,
          selectedMode: false
        },
        series: [{
          type: 'graph',
          layout: 'force',
          data: nodes,
          links: links,
          categories: [
            { name: '目标材料' },
            { name: '选中替代材料' },
            { name: '共同下游产品' },
            { name: '其他节点' }
          ],
          roam: true,
          label: {
            show: true,
            position: 'right',
            formatter: '{b}'
          },
          force: {
            repulsion: 100,
            edgeLength: [50, 100]
          },
          lineStyle: {
            color: '#aaa',
            curveness: 0.3
          },
          emphasis: {
            focus: 'adjacency',
            lineStyle: {
              width: 2
            }
          }
        }]
      };
      
      graphChart.setOption(option);
      
      // 自适应大小
      window.addEventListener('resize', () => {
        graphChart && graphChart.resize();
      });
    };
    
    // 导出数据
    const handleExport = () => {
      emit('export', props.data);
    };
    
    // 组件挂载后初始化
    onMounted(() => {
      if (substitutes.value.length > 0) {
        // 默认选择第一个替代品
        selectedSubstitute.value = substitutes.value[0].potentialSubstitute;
        renderGraph();
      }
    });
    
    // 监听数据变化
    watch(() => props.data, () => {
      if (substitutes.value.length > 0) {
        // 默认选择第一个替代品
        selectedSubstitute.value = substitutes.value[0].potentialSubstitute;
        setTimeout(() => {
          renderGraph();
        }, 300);
      }
    }, { deep: true });
    
    return {
      graphRef,
      targetMaterial,
      substitutes,
      selectedSubstitute,
      selectedSubstituteData,
      handleRowClick,
      getSimilarityColor,
      getSimilarityTagType,
      getSupplierCountType,
      handleExport
    };
  }
};
</script>

<style scoped>
.substitute-analysis-result {
  padding: 20px;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.result-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.analysis-description {
  margin-bottom: 20px;
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border-left: 4px solid #409EFF;
}

h4 {
  font-size: 16px;
  margin: 20px 0 15px;
  color: #303133;
}

h5 {
  font-size: 14px;
  margin: 15px 0 10px;
  color: #606266;
}

.substitute-table-container, 
.substitute-detail {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 16px;
  height: 100%;
  min-height: 350px;
}

.material-name {
  cursor: pointer;
}

.material-name.selected {
  font-weight: bold;
  color: #409EFF;
}

.similarity-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.similarity-metrics {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.metric {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.metric-label {
  font-size: 13px;
  color: #909399;
}

.metric-value {
  font-size: 14px;
  font-weight: 500;
}

.common-products {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-top: 5px;
}

.product-tag {
  margin-bottom: 5px;
}

.substitute-graph-container {
  margin-top: 30px;
}

.substitute-graph {
  width: 100%;
  height: 400px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.el-progress-bar__inner) {
  transition: width 0.3s ease;
}

:deep(.el-table .cell) {
  line-height: 1.5;
  word-break: break-word;
}
</style> 